import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Badge } from '@/components/ui/badge';
import { Container } from '@/components/common/container';
import { X, Plus, Calendar, Users, Clock, Link } from 'lucide-react';

const TaskForm = ({ task, onSubmit, onCancel, projects = [] }) => {
  const [formData, setFormData] = useState({
    task_name: '',
    project_id: '',
    description: '',
    assignee_name: '',
    participants: [],
    start_date: '',
    end_date: '',
    estimated_hours: '',
    actual_hours: '',
    status: '未开始',
    priority: '中',
    progress_percentage: 0,
    predecessor_tasks: [],
    successor_tasks: [],
    remarks: ''
  });

  const [newParticipant, setNewParticipant] = useState('');
  const [newPredecessor, setNewPredecessor] = useState('');
  const [newSuccessor, setNewSuccessor] = useState('');
  const [loading, setLoading] = useState(false);

  // 模拟团队成员数据
  const teamMembers = ['张三', '李四', '王五', '赵六', '钱七', '孙八', '周九', '吴十'];

  // 初始化表单数据
  useEffect(() => {
    if (task) {
      setFormData({
        task_name: task.task_name || '',
        project_id: task.project_id || '',
        description: task.description || '',
        assignee_name: task.assignee_name || '',
        participants: task.participants || [],
        start_date: task.start_date || '',
        end_date: task.end_date || '',
        estimated_hours: task.estimated_hours || '',
        actual_hours: task.actual_hours || '',
        status: task.status || '未开始',
        priority: task.priority || '中',
        progress_percentage: task.progress_percentage || 0,
        predecessor_tasks: task.predecessor_tasks || [],
        successor_tasks: task.successor_tasks || [],
        remarks: task.remarks || ''
      });
    }
  }, [task]);

  // 处理表单字段变化
  const handleFieldChange = (field, value) => {
    setFormData(prev => ({ ...prev, [field]: value }));
  };

  // 添加参与者
  const handleAddParticipant = () => {
    if (newParticipant.trim() && !formData.participants.includes(newParticipant.trim())) {
      setFormData(prev => ({
        ...prev,
        participants: [...prev.participants, newParticipant.trim()]
      }));
      setNewParticipant('');
    }
  };

  // 移除参与者
  const handleRemoveParticipant = (participant) => {
    setFormData(prev => ({
      ...prev,
      participants: prev.participants.filter(p => p !== participant)
    }));
  };

  // 添加前置任务
  const handleAddPredecessor = () => {
    if (newPredecessor.trim() && !formData.predecessor_tasks.includes(newPredecessor.trim())) {
      setFormData(prev => ({
        ...prev,
        predecessor_tasks: [...prev.predecessor_tasks, newPredecessor.trim()]
      }));
      setNewPredecessor('');
    }
  };

  // 移除前置任务
  const handleRemovePredecessor = (task) => {
    setFormData(prev => ({
      ...prev,
      predecessor_tasks: prev.predecessor_tasks.filter(t => t !== task)
    }));
  };

  // 添加后置任务
  const handleAddSuccessor = () => {
    if (newSuccessor.trim() && !formData.successor_tasks.includes(newSuccessor.trim())) {
      setFormData(prev => ({
        ...prev,
        successor_tasks: [...prev.successor_tasks, newSuccessor.trim()]
      }));
      setNewSuccessor('');
    }
  };

  // 移除后置任务
  const handleRemoveSuccessor = (task) => {
    setFormData(prev => ({
      ...prev,
      successor_tasks: prev.successor_tasks.filter(t => t !== task)
    }));
  };

  // 处理表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 生成任务编号（实际项目中应该由后端生成）
      const taskCode = task ? task.task_code : `TASK-${new Date().getFullYear()}-${String(Math.floor(Math.random() * 1000)).padStart(3, '0')}`;
      
      const submitData = {
        ...formData,
        task_code: taskCode,
        estimated_hours: parseFloat(formData.estimated_hours) || 0,
        actual_hours: parseFloat(formData.actual_hours) || 0,
        progress_percentage: parseInt(formData.progress_percentage) || 0
      };
      
      onSubmit && onSubmit(submitData);
    } catch (error) {
      console.error('保存任务失败:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Container>
      <Card>
        <CardHeader>
          <CardTitle>{task ? '编辑任务' : '创建任务'}</CardTitle>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-6">
            {/* 基本信息 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              <div className="space-y-2">
                <Label htmlFor="task_name">任务名称 *</Label>
                <Input
                  id="task_name"
                  value={formData.task_name}
                  onChange={(e) => handleFieldChange('task_name', e.target.value)}
                  placeholder="请输入任务名称"
                  required
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="project_id">所属项目 *</Label>
                <Select value={formData.project_id} onValueChange={(value) => handleFieldChange('project_id', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择项目" />
                  </SelectTrigger>
                  <SelectContent>
                    {projects.map(project => (
                      <SelectItem key={project.id} value={project.id}>
                        {project.project_name}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="assignee_name">负责人 *</Label>
                <Select value={formData.assignee_name} onValueChange={(value) => handleFieldChange('assignee_name', value)}>
                  <SelectTrigger>
                    <SelectValue placeholder="请选择负责人" />
                  </SelectTrigger>
                  <SelectContent>
                    {teamMembers.map(member => (
                      <SelectItem key={member} value={member}>
                        {member}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="priority">优先级</Label>
                <Select value={formData.priority} onValueChange={(value) => handleFieldChange('priority', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="高">高</SelectItem>
                    <SelectItem value="中">中</SelectItem>
                    <SelectItem value="低">低</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="status">任务状态</Label>
                <Select value={formData.status} onValueChange={(value) => handleFieldChange('status', value)}>
                  <SelectTrigger>
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="未开始">未开始</SelectItem>
                    <SelectItem value="进行中">进行中</SelectItem>
                    <SelectItem value="已完成">已完成</SelectItem>
                    <SelectItem value="已暂停">已暂停</SelectItem>
                    <SelectItem value="已取消">已取消</SelectItem>
                  </SelectContent>
                </Select>
              </div>

              <div className="space-y-2">
                <Label htmlFor="progress_percentage">进度百分比</Label>
                <Input
                  id="progress_percentage"
                  type="number"
                  min="0"
                  max="100"
                  value={formData.progress_percentage}
                  onChange={(e) => handleFieldChange('progress_percentage', e.target.value)}
                  placeholder="0-100"
                />
              </div>
            </div>

            {/* 时间安排 */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="space-y-2">
                <Label htmlFor="start_date">开始时间</Label>
                <Input
                  id="start_date"
                  type="date"
                  value={formData.start_date}
                  onChange={(e) => handleFieldChange('start_date', e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="end_date">结束时间</Label>
                <Input
                  id="end_date"
                  type="date"
                  value={formData.end_date}
                  onChange={(e) => handleFieldChange('end_date', e.target.value)}
                />
              </div>

              <div className="space-y-2">
                <Label htmlFor="estimated_hours">预计工时</Label>
                <Input
                  id="estimated_hours"
                  type="number"
                  step="0.5"
                  min="0"
                  value={formData.estimated_hours}
                  onChange={(e) => handleFieldChange('estimated_hours', e.target.value)}
                  placeholder="小时"
                />
              </div>
            </div>

            {/* 任务描述 */}
            <div className="space-y-2">
              <Label htmlFor="description">任务描述</Label>
              <Textarea
                id="description"
                value={formData.description}
                onChange={(e) => handleFieldChange('description', e.target.value)}
                placeholder="请输入任务描述"
                rows={4}
              />
            </div>

            {/* 参与者 */}
            <div className="space-y-2">
              <Label className="flex items-center gap-2">
                <Users className="size-4" />
                参与者
              </Label>
              <div className="flex gap-2">
                <Select value={newParticipant} onValueChange={setNewParticipant}>
                  <SelectTrigger className="flex-1">
                    <SelectValue placeholder="选择参与者" />
                  </SelectTrigger>
                  <SelectContent>
                    {teamMembers.map(member => (
                      <SelectItem key={member} value={member}>
                        {member}
                      </SelectItem>
                    ))}
                  </SelectContent>
                </Select>
                <Button type="button" variant="outline" onClick={handleAddParticipant}>
                  <Plus className="size-4" />
                </Button>
              </div>
              {formData.participants.length > 0 && (
                <div className="flex flex-wrap gap-2 mt-2">
                  {formData.participants.map((participant, index) => (
                    <Badge key={index} variant="secondary" className="gap-1">
                      {participant}
                      <button
                        type="button"
                        onClick={() => handleRemoveParticipant(participant)}
                        className="ml-1 hover:text-destructive"
                      >
                        <X className="size-3" />
                      </button>
                    </Badge>
                  ))}
                </div>
              )}
            </div>

            {/* 任务依赖关系 */}
            <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
              {/* 前置任务 */}
              <div className="space-y-2">
                <Label className="flex items-center gap-2">
                  <Link className="size-4" />
                  前置任务
                </Label>
                <div className="flex gap-2">
                  <Input
                    value={newPredecessor}
                    onChange={(e) => setNewPredecessor(e.target.value)}
                    placeholder="输入任务编号"
                  />
                  <Button type="button" variant="outline" onClick={handleAddPredecessor}>
                    <Plus className="size-4" />
                  </Button>
                </div>
                {formData.predecessor_tasks.length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-2">
                    {formData.predecessor_tasks.map((task, index) => (
                      <Badge key={index} variant="outline" className="gap-1">
                        {task}
                        <button
                          type="button"
                          onClick={() => handleRemovePredecessor(task)}
                          className="ml-1 hover:text-destructive"
                        >
                          <X className="size-3" />
                        </button>
                      </Badge>
                    ))}
                  </div>
                )}
              </div>

              {/* 后置任务 */}
              <div className="space-y-2">
                <Label className="flex items-center gap-2">
                  <Link className="size-4" />
                  后置任务
                </Label>
                <div className="flex gap-2">
                  <Input
                    value={newSuccessor}
                    onChange={(e) => setNewSuccessor(e.target.value)}
                    placeholder="输入任务编号"
                  />
                  <Button type="button" variant="outline" onClick={handleAddSuccessor}>
                    <Plus className="size-4" />
                  </Button>
                </div>
                {formData.successor_tasks.length > 0 && (
                  <div className="flex flex-wrap gap-2 mt-2">
                    {formData.successor_tasks.map((task, index) => (
                      <Badge key={index} variant="outline" className="gap-1">
                        {task}
                        <button
                          type="button"
                          onClick={() => handleRemoveSuccessor(task)}
                          className="ml-1 hover:text-destructive"
                        >
                          <X className="size-3" />
                        </button>
                      </Badge>
                    ))}
                  </div>
                )}
              </div>
            </div>

            {/* 备注 */}
            <div className="space-y-2">
              <Label htmlFor="remarks">备注</Label>
              <Textarea
                id="remarks"
                value={formData.remarks}
                onChange={(e) => handleFieldChange('remarks', e.target.value)}
                placeholder="请输入备注信息"
                rows={3}
              />
            </div>

            {/* 操作按钮 */}
            <div className="flex gap-4 pt-4">
              <Button type="submit" disabled={loading}>
                {loading ? '保存中...' : (task ? '更新任务' : '创建任务')}
              </Button>
              <Button type="button" variant="outline" onClick={onCancel}>
                取消
              </Button>
            </div>
          </form>
        </CardContent>
      </Card>
    </Container>
  );
};

export default TaskForm; 